<template>
  <component
    :is="formKey"
    v-if="isInit"
    ref="auditForm"
    v-bind="config"
    @save="saveForm"
  />
</template>

<script>
import { GetOutline } from '@/customForm/api/form'

import Vue from 'vue'
export default {
  components: {},
  props: {
    linkPk: {
      type: String,
      default: null
    },
    linkType: {
      type: String,
      default: null
    },
    pageType: {
      type: Number,
      default: 0
    },
    power: {
      type: Object,
      default: null
    },
    fillData: {
      type: Object,
      default: null
    },
    readonly: {
      type: Boolean,
      default: false
    },
    formId: {
      type: String,
      default: null
    },
    isLoad: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      source: null,
      formKey: 'auditForm',
      isInit: false,
      config: {},
      pagePath: null
    }
  },
  computed: {
    comId() {
      return this.$store.getters.curComId
    }
  },
  watch: {
    isLoad: {
      handler(val) {
        if (val) {
          this.reset()
        }
      },
      immediate: true
    },
    readonly: {
      handler(val) {
        if (val && this.isInit) {
          this.resetForm()
        }
      },
      immediate: false
    }
  },
  mounted() {},
  methods: {
    saveForm() {
      this.$emit('save')
    },
    async save() {
      if (this.config.readonly) {
        return
      }
      this.$refs['auditForm'].save()
    },
    resetForm() {
      this.config.readonly = true
      this.formKey = 'Form_' + this.formId + '_' + this.linkPk + '_' + this.config.readonly
      const path = this.pagePath
      Vue.component(this.formKey, function(resolve, reject) {
        require(['@/' + path + '.vue'], resolve)
      })
    },
    async reset() {
      this.config.formId = this.formId
      this.config.readonly = this.readonly || this.pageType !== 1
      this.config.linkPk = this.linkPk
      this.config.linkType = this.linkType
      this.config.power = this.power
      this.config.formVal = this.fillData
      this.config.isShowSaveBtn = false
      this.config.isLoad = true
      const form = await GetOutline(this.formId, this.pageType)
      this.source = form
      let path = null
      if (form.FormType !== 0) {
        path = form.PagePath
      } else {
        path = 'customForm/components/userForm/userForm'
      }
      this.pagePath = path
      this.formKey = 'Form_' + this.formId + '_' + this.linkPk + '_' + this.config.readonly
      Vue.component(this.formKey, function(resolve, reject) {
        require(['@/' + path + '.vue'], resolve)
      })
      this.isInit = true
    }
  }
}
</script>
